package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func dbInit() (err error) {
	dsn := "root:xxx@tcp(127.0.0.1:3306)/cmdb2"
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		fmt.Println("dsn错误:%v", err)
		return
	}
	err = db.Ping()
	if err != nil {
		return err
	}
	return nil

}

type user struct {
	id    int
	name  string
	email string
}

func queryOneRow(id int) {
	sqlStr := "SELECT id,username,email FROM `cmdb2`.`sql_users` WHERE `id` = ? LIMIT 0, 1000"
	var user1 user
	err := db.QueryRow(sqlStr, id).Scan(&user1.id, &user1.name, &user1.email)
	if err != nil {
		fmt.Println("查询单挑数据出错：%v", err)
		return
	}
	fmt.Printf("id:%d name:%s email:%s\n", user1.id, user1.name, user1.email)
}

func main() {
	err := dbInit()
	if err != nil {
		fmt.Printf("init db failed,err:%v\n", err)
		return
	}
	queryOneRow(2)
}
